﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using WebCamView.Code;
using WebCamView.ServiceReference1;
using WebCamView.Views.Controls;
using System.IO;

namespace WebCamView.Views
{
    public partial class WebChat : UserControl
    {
       
        //private List<ServiceReference1>

        private MetaCamInfo _myInfo = new MetaCamInfo() { FpsRate=20, MaxResolutionHeight=200, MaxResolutionWidth=300, RefreshTime=10, };
        
        public WebChat()
        {
            InitializeComponent();
            WebCamServer.Client.JoinCompleted += new EventHandler<JoinCompletedEventArgs>(onJoin);
            WebCamServer.Client.GetFullListCompleted += new EventHandler<GetFullListCompletedEventArgs>(onRefresh);
            //this.participantsPanel.ItemsSource = CamRepository.Instance
            //WebCamServer.Client.JoinAsync(_myInfo);
        }

        private void onJoin(object sender, JoinCompletedEventArgs args)
        {
            refreshCamList(args.Result.ToArray());
        }

        /// <summary>
        /// do complete replace of current childs list by another
        /// </summary>
        /// <param name="cameras"></param>
        private void refreshCamList(MetaCamInfo [] cameras)
        {
            participants.Children.Clear();
            cameras.All((camera) =>
            {
                var testCamControl = new CamControl() { Info = camera };
                participants.Children.Add(testCamControl);
                return true;
            });
            label2.Content = cameras.Length;
        }

        private void refreshBtn_Click(object sender, RoutedEventArgs e)
        {
            WebCamServer.Client.GetFullListAsync();
        }

        private void onRefresh(object sender, GetFullListCompletedEventArgs args)
        {
            refreshCamList(args.Result.ToArray());
        }

        private void join_Click(object sender, RoutedEventArgs e)
        {
            _myInfo.Name = name.Text;
            WebCamServer.Client.JoinAsync(_myInfo);
            webCamConnect();
        }

        //WEB CAM PART

        private CaptureSource _captureSource = new CaptureSource();
        

        private void webCamConnect()
        {
            if (_captureSource != null)
            {
                _captureSource.Stop();

                _captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
                _captureSource.AudioCaptureDevice = CaptureDeviceConfiguration.GetDefaultAudioCaptureDevice();

                VideoBrush vidBrush = new VideoBrush();
                vidBrush.SetSource(_captureSource);

                videoRect.Fill = vidBrush;

                if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess())
                {
                    _captureSource.Start();
                }
            }
        }

        private void webCamDisconnect()
        {
            if (_captureSource != null)
            {
                _captureSource.Stop();
            }    
        }

        private void takeSnapshot_Click(object sender, RoutedEventArgs e)
        {
            if (_captureSource != null)
            {
                _captureSource.AsyncCaptureImage((snapImage) =>
                {
                    using (MemoryStream _ms = new MemoryStream())
                    {
                        ImageTools.EncodeJpeg(snapImage, _ms);
                        _ms.Flush();
                        var imageBytes = _ms.ToArray();
                        try
                        {
                            var width = _captureSource.VideoCaptureDevice.DesiredFormat.Width;
                            var height = _captureSource.VideoCaptureDevice.DesiredFormat.Height;

                        }
                        catch (Exception)
                        {
                            new ChildWindow() { Content = "Error accessing resolution of the cam" }.Show();
                        } 
                        WebCamServer.Client.SendImageAsync(_myInfo, new ImageData() { Content = imageBytes, Width = 100, Height = 120 });
                        sendSnapshotMessage.Content = "sent image (" + imageBytes.Length + " bytes)";
                    }
                });
            }
        }
        
    }
}
